package com.ruoyi.system.task;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysUserService;

/**
 * 工号自动清理任务
 * 定时清理已删除用户的工号，确保工号可以被重新使用
 * 
 * @author ruoyi
 */
@Component("employeeIdCleanupTask")
public class EmployeeIdCleanupTask
{
    private static final Logger log = LoggerFactory.getLogger(EmployeeIdCleanupTask.class);

    @Autowired
    private ISysUserService userService;

    /**
     * 自动清理已删除用户的工号
     */
    public void cleanupDeletedUserEmployeeIds()
    {
        try
        {
            log.info("开始执行工号自动清理任务...");
            
            // 查询所有已删除且有工号的用户
            SysUser queryUser = new SysUser();
            queryUser.setDelFlag("2"); // 已删除状态
            
            List<SysUser> deletedUsers = userService.selectUserList(queryUser);
            int cleanedCount = 0;
            
            for (SysUser user : deletedUsers)
            {
                if (StringUtils.isNotEmpty(user.getEmployeeId()))
                {
                    // 回收工号
                    int result = userService.recycleEmployeeId(user.getEmployeeId());
                    if (result > 0)
                    {
                        cleanedCount++;
                        log.info("自动清理工号成功：用户ID={}, 用户名={}, 工号={}", 
                                user.getUserId(), user.getUserName(), user.getEmployeeId());
                    }
                }
            }
            
            log.info("工号自动清理任务完成，共清理 {} 个工号", cleanedCount);
        }
        catch (Exception e)
        {
            log.error("工号自动清理任务执行失败", e);
        }
    }
}
